/**
 * @Author: wangjian
 * 656876071@qq.com
 * @Date: 2024-09-14 09:31:55
 * @LastEditTime: 2024-09-29 10:17:33
 * @FilePath: src/stores/Core.ts
 * @Description:
 */
import {defineStore} from "pinia";
import userInfoApi, {type VueRouteObj} from "@/core/api/sys/UserInfoApi";
import {defineAsyncComponent, ref} from "vue";
import type {Router, RouteRecordRaw} from "vue-router";
import type {SysMenuTree} from "@/views/sys/api/SysMenuApi";
const {getVueRoutes,getMenuTree} = userInfoApi()

export const useUserInfoStore = defineStore('coreUserInfo', () => {


    return {}
})

export const useGlobalRouteAndPermStore = defineStore("core_route_perm", () => {
    const routes = ref<RouteRecordRaw[]>([])

    const initBuildRoute = async (router: Router) => {
        if (routes.value.length == 0)
            await buildRoutes(router)
    }
    const buildRoutes = async (router: Router) => {
        await getVueRoutes().then(res => {
            return res.data
        }).then(routesData => {
            routes.value =
                routesData.map((route: VueRouteObj) => {
                    let vueRoute = {
                        path: route.path,
                        component: resolveComponent(route.component),
                        name: route.name,
                    } as RouteRecordRaw

                    router.addRoute('root', vueRoute)
                    return vueRoute
                })
            return routesData
        })
    }

    return {
        routes,
        initBuildRoute,
        buildRoutes
    }
})

export const useGlobalMenuStore = defineStore("core_menu", () => {
    const menuTree = ref<SysMenuTree[]>([])
    const initMenu = ()=>{
        return getMenuTree().then(res=>{
            menuTree.value = res.data
            return res.data
        })
    }
    
    return {
        menuTree,
        initMenu
    }
})

/**
 * 动态加载组件,必须使用方法封装defineAsyncComponent
 * @param component
 */
const resolveComponent = (component: string) => {
    // return defineAsyncComponent(() => import('..'+component+'.vue'))
    return defineAsyncComponent(() => import(/* @vite-ignore */`..${component}.vue`))
}